<template>
  <div>
    <p>递归遍历模型树结构、查询模型节点</p>
    <div class="three_box"></div>
  </div>
</template>

<script setup>
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { nextTick } from "vue";
nextTick(() => {
  const DOM = document.querySelector(".three_box");
  const width = DOM.offsetWidth;
  const height = DOM.offsetHeight;
  // 场景
  const scene = new THREE.Scene();
  scene.name = "场景";
  //   坐标轴
  const xyz = new THREE.AxesHelper(100);
  scene.add(xyz);

  let group = new THREE.Group();
  group.name = "矮楼";
  for (let index = 0; index < 5; index++) {
    // 材质
    const material = new THREE.MeshBasicMaterial({
      color: 0x00ffff,
      transparent: true,
      opacity: 0.7,
    });
    // 几何图形
    let geo = new THREE.BoxGeometry(40, 40, 40);
    let mesh = new THREE.Mesh(geo, material);
    //   模型
    mesh.position.set(index * 50, 0, 0);
    mesh.name = "1-" + index + "号楼";
    group.add(mesh);
  }
  let group1 = new THREE.Group();
  group1.name = "高楼";
  for (let index = 0; index < 5; index++) {
    // 材质
    const material = new THREE.MeshBasicMaterial({
      color: 0x00ffff,
      transparent: true,
      opacity: 0.7,
    });
    // 几何图形
    let geo = new THREE.BoxGeometry(40, 150, 20);
    let mesh = new THREE.Mesh(geo, material);
    //   模型
    mesh.position.set(index * 50, 0, -80);
    mesh.name = "2-" + index + "号楼";
    group1.add(mesh);
  }
  let groups = new THREE.Group();
  groups.name = "小区";
  groups.add(group, group1);
  scene.add(groups);
  //  光源
  const light = new THREE.AmbientLight(0xffffff, 0.1);
  scene.add(light);
  //  相机
  const camera = new THREE.PerspectiveCamera(30, width / height, 0.1, 30000);
  camera.position.set(350, 350, 350);
  camera.lookAt(200, 150, 0);
  //   渲染画布
  const renderer = new THREE.WebGLRenderer({
    antialias: true,
  });
  renderer.setSize(width, height);
  renderer.setClearColor(0x000000);
  DOM.appendChild(renderer.domElement);
  //   像素比
  renderer.setPixelRatio(window.devicePixelRatio);
  //   控件
  const controls = new OrbitControls(camera, renderer.domElement);
  controls.addEventListener("change", function () {
    renderer.render(scene, camera);
  });

  // 递归遍历所有的节点------------------------------------------------------------
  groups.traverse(function (obj) {
    // console.log("name：", obj.name);
    // 判断是不是网格模型
    if (obj.isMesh) {
      console.log(obj.name + ":是网格模型");
    }
  });
  //   查找某个网格模型对象------------------
  const obj = groups.getObjectByName("2-3号楼");
  obj.material.color.set(0xff0000);

    //   执行渲染
    renderer.render(scene, camera);
});
</script>

<style scoped>
.three_box {
  width: 60vw;
  height: 60vh;
}
</style>